package com.wufeng.mycode;


import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 资源类
 */
class SourceData {
    private boolean FLAG = true;
    private AtomicInteger atomicInteger = new AtomicInteger();
    private BlockingQueue<String> blockingQueue = null;

    SourceData(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());
    }

    // 生产者
    public void prod() throws Exception {
        String data = null;
        while (FLAG) {
            data = atomicInteger.getAndIncrement() + "";
            boolean result = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
            if (result) {
                System.out.println(Thread.currentThread().getName() + "\t 生成成功-" + data);
            } else {
                System.out.println(Thread.currentThread().getName() + "\t 生成失败" + data);
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println();
        System.out.println();
        System.out.println(Thread.currentThread().getName() + "\t 生产结束");
    }

    // 消费者
    public void consumer() throws Exception {
        String data = null;
        while (FLAG) {
            data = blockingQueue.poll(2, TimeUnit.SECONDS);
            if (data == null || "".equals(data)) {
                FLAG = false;
                System.out.println(Thread.currentThread().getName() + "\t 消费超时或未有生产品可消费");
                return;
            }
            System.out.println(Thread.currentThread().getName() + "\t 消费成功-" + data);
            System.out.println();
        }
    }

    public void stop() {
        FLAG = false;
    }
}

public class BlockingQueueDemo {
    public static void main(String[] args) {
//        SourceData sourceData = new SourceData(new LinkedBlockingDeque<String>());
        SourceData sourceData = new SourceData(new ArrayBlockingQueue<String>(3));
        new Thread(() -> {
            try {
                sourceData.prod();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "生产线程").start();

        new Thread(() -> {
            try {
                sourceData.consumer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "消费线程").start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        sourceData.stop();
    }
}
